package com.example.qihuibao.widget.view

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.qihuibao.R
import com.example.qihuibao.bean.EmpType
import com.example.qihuibao.bean.ReqUpdateEnterpriseInfoBean
import com.example.qihuibao.module.main.MainActivity
import com.example.qihuibao.utils.extension.toast

/**
 *     author : cwwei
 *     e-mail : 494545699@qq.com
 *     date   : 2022/08/13
 *     desc   :
 */
class EnterpriseInfoLayout(ctx:Context) : FrameLayout(ctx) {
    private lateinit var activity:MainActivity
    private lateinit var root:View
    private var modify = false
    private val empTypeList = mutableListOf<EmpType>()
    private lateinit var rv_employ:CommonRecyclerView

    init {
        if (ctx is MainActivity) {
            activity = ctx
        }
        root = LayoutInflater.from(ctx).inflate(R.layout.layout_enterpriseinfo, this, true)
        root.setOnClickListener {  }//禁止点击事件穿透
        initView()
    }

    private fun initView() {
        val tvRight1 = root.findViewById<TextView>(R.id.tv_tv_right1)
        val tvRight2 = root.findViewById<TextView>(R.id.tv_tv_right2)
        tvRight1.text = "修改"
        tvRight2.text = "更新"
        tvRight1.visibility = View.VISIBLE
        tvRight2.visibility = View.VISIBLE
        tvRight1.setOnClickListener {
            modify = !modify
            tvRight1.text = if(modify) "取消" else "修改"
            setModify()
            if (!modify) {
                getEnterpriseInfo()
            }
        }
        tvRight2.setOnClickListener {
            if (modify) {
                update()
            }else {
                activity.toast("先点击修改")
            }
        }
        root.findViewById<View>(R.id.iv_back).setOnClickListener { (parent as ViewGroup).removeView(this) }
        root.findViewById<TextView>(R.id.tv_title).text = "企业信息"
        getEnterpriseInfo()
    }

    private fun getEnterpriseInfo() {
        activity.getMainViewModel().queryEnterpriseInfo().observe(activity) {
            if (it.RetCode == "0") {
                root.findViewById<TextView>(R.id.tv1)?.text = "企业名称：${it.CorpName}\n" +
                        "状态：${if (it.BindFlag == "0") "正常" else "冻结"}\n" +
                        "系统对接模式：${when(it.AccountStandard) {
                            "1" -> "企慧宝"
                            "2" -> "外部系统"
                            "3" -> "企慧宝电子钱包"
                            else -> ""
                        }}\n" +
                        "关系人绑定开关：${if (it.BindFlag == "0") "关" else "开"}\n" +
                        "单位外绑定开关：${if (it.OuterBindFlag == "0") "关" else "开"}\n" +
                        "亲友绑定开关及方式：${when(it.AccountStandard) {
                            "0" -> "关闭"
                            "1" -> "预留信息"
                            "2" -> "身份证后6位"
                            else -> ""
                        }}\n" +
                        "个人账户余额上限：${it.PerBalanceLimit}\n" +
                        "单笔充值限额：${it.RechargeAmtLimit}\n" +
                        "日累计充值限额：${it.DailyRechargeAmtLimit}\n" +
                        "单笔退款限额：${it.RefundAmtLimit}\n" +
                        "日累计退款限额：${it.DailyRefundAmtLimit}\n" +
                        "透支限额：${it.OverdraftLimit}\n" +
                        "充值提醒开关：${if (it.RemindSmsFlag == "0") "关" else "开"}\n" +
//                        "充值提醒阀值：${it.RemindSmsThreshold}\n" +
                        "电子餐票开关：${if (it.ETicketFlag == "0") "关" else "开"}\n"
                root.findViewById<EdittextWithText>(R.id.et_RemindSmsThreshold)?.setContent("${it.RemindSmsThreshold}")
                //
                empTypeList.clear()
                if (!it.EmpTypeList.isNullOrEmpty()) {
                    empTypeList.addAll(it.EmpTypeList)
                }
                rv_employ = root.findViewById<CommonRecyclerView>(R.id.rv_employ)
                rv_employ.init(
                    R.layout.item_emptype_with_add_delete,
                    LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                    empTypeList,
                    {parent, pos ->
                        if (empTypeList.isNotEmpty()) {
                            val et_EmpTypeID = parent.findViewById<EdittextWithText>(R.id.et_EmpTypeID)
                            val et_EmpTypeName = parent.findViewById<EdittextWithText>(R.id.et_EmpTypeName)
                            et_EmpTypeID.setContentWithModify(empTypeList[pos].EmpTypeID) {s -> empTypeList[pos].EmpTypeID = s }
                            et_EmpTypeName.setContentWithModify(empTypeList[pos].EmpTypeName) {s -> empTypeList[pos].EmpTypeName = s }
                            et_EmpTypeID.enableContent(modify)
                            et_EmpTypeName.enableContent(modify)
                            if (empTypeList[pos].EmpTypeID.isEmpty()) {//empty
                                parent.findViewById<View>(R.id.ll_content).visibility = View.GONE
                                parent.findViewById<View>(R.id.iv_delete).visibility = View.GONE
                                parent.findViewById<View>(R.id.iv_add).visibility = View.VISIBLE
                            }else {
                                parent.findViewById<View>(R.id.ll_content).visibility = View.VISIBLE
                                parent.findViewById<View>(R.id.iv_delete).visibility = if (modify) View.VISIBLE else View.GONE
                                parent.findViewById<View>(R.id.iv_add).visibility = View.GONE
                            }
                            parent.findViewById<View>(R.id.iv_delete).setOnClickListener {
                                empTypeList.removeAt(pos)
                                rv_employ.adapter?.notifyDataSetChanged()
                            }
                            parent.findViewById<View>(R.id.iv_add).setOnClickListener {
                                empTypeList.add(empTypeList.size-1, EmpType("1", ""))
                                rv_employ.adapter?.notifyDataSetChanged()
                            }
                        }
                    }
                )
                root.findViewById<CommonRecyclerView>(R.id.rv_canteen)?.init(
                    R.layout.item_text,
                    LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                    it.CantList,
                    {parent, pos ->
                        (parent as TextView).text = "餐厅名称：${it.CantList!![pos].CantName}\n" +
                                "状态：${if (it.CantList!![pos].Status=="0") "正常" else "冻结"}"
                    }
                )
                root.findViewById<CommonRecyclerView>(R.id.rv_eticket)?.init(
                    R.layout.item_etickettype,
                    LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                    it.ETicketTypeList,
                    {parent, pos ->
                        (parent as TextView).text = activity.getString(R.string.eticket_name, it.ETicketTypeList!![pos].ETicketName) + "\n" +
                                activity.getString(R.string.status, if (it.ETicketTypeList!![pos].Status=="0") "不开通" else "开通")
                    }
                )
            }
        }
    }

    private fun setModify() {
        root.findViewById<EdittextWithText>(R.id.et_RemindSmsThreshold)?.enableContent(modify)
        if (modify) {
            empTypeList.add(EmpType())
        }else {
            if (empTypeList.isNotEmpty() && empTypeList.last().EmpTypeID.isEmpty()) {
                empTypeList.removeLast()
            }
        }
        rv_employ.adapter?.notifyDataSetChanged()
    }

    private fun update() {
        val value = root.findViewById<EdittextWithText>(R.id.et_RemindSmsThreshold)?.getContent()
        if (value.isNullOrEmpty()) {
            activity.toast("阈值不能为空")
            return
        }
        if (empTypeList.last().EmpTypeID.isEmpty()) {
            empTypeList.removeLast()
        }
        val idMap = hashMapOf<String, String>()
        for (item in empTypeList) {
            if (idMap[item.EmpTypeID] == null) {
                idMap[item.EmpTypeID] = item.EmpTypeName
            }else {
                activity.toast("ID不能相同")
                return
            }
        }
        val req = ReqUpdateEnterpriseInfoBean()
        req.RemindSmsThreshold = value.toInt()
        req.EmpTypeList = empTypeList
        activity.getMainViewModel().updateEnterpriseInfo(req).observe(activity) {
            activity.toast("${if (it.RetCode == "0") "更新成功" else "更新失败：${it.RetMsg}"}")
            if (modify) {
                root.findViewById<TextView>(R.id.tv_tv_right1).performClick()
            }
        }
    }
}